<template>
  <div class="about">
    <div class="container">
      <div style="margin: 20px 0">
        <el-input placeholder="请输入新闻标题" v-model="title" style="width: 200px;"></el-input>
        <el-input placeholder="请输入新闻简介" v-model="description" style="width: 200px; margin: 0 10px"></el-input>
        <el-button type="primary" @click="load(pageNum)">查询</el-button>
        <el-button type="warning" @click="returnInfo">重置</el-button>
      </div>

      <div style="margin: 20px 0">
        <el-button type="primary" @click="FormAddInfoAn" plain>添加数据</el-button>
        <el-button type="danger" @click="deleteBatch">批量删除</el-button>
      </div>

      <el-table :data="tableData" @selection-change="handleSelectionChange" style="border-radius: 10px"
                :header-cell-style="{background:'aliceblue',height:'45px', color:'#666'}">
        <el-table-column type="selection" align="center" width="55"></el-table-column>
        <el-table-column align="center" prop="title" label="标题"></el-table-column>
        <el-table-column align="center" prop="description" label="简介"></el-table-column>
        <el-table-column align="center" prop="content" label="内容">
            <template v-slot="scope">
              <el-button @click="showContent(scope.row.content)" size="mini">显示内容</el-button>
            </template>
        </el-table-column>
        <el-table-column align="center" prop="authorid" label="发布人">
          <template #default="scope">
            {{
              scope.row.authorid === 0 ? '大众作者' :
              scope.row.authorid === 1 ? '主编作者' :
              scope.row.authorid === 25 ? '管理员' : '未知'
            }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="time" label="发布时间"></el-table-column>
        <el-table-column align="center" width="170px" label="操作">
          <template v-slot="scope" style="width: 340px">
            <el-button style="width: 65px; margin-right: 10px" type="success" plain @click="handleEdit(scope.row)">编辑
            </el-button>
            <el-button style="width: 65px;" type="danger" plain @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block" style="margin: 20px 0">
        <el-pagination
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-size="pageSize"
            layout="total, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </div>

      <el-dialog title="添加新闻" :visible.sync="FormAddInfo" width="55%" @close="onClose">
        <el-form label-width="80px" style="padding-right: 30px" ref="formRef" :rules="rules" :model="users"
                 class="demo-form-inline">
          <el-form-item prop="title" style="margin-top: 30px;" label="标题">
            <el-input v-model="users.title"></el-input>
          </el-form-item>

          <el-form-item prop="description" style="margin-left: 2px" label="简介">
            <el-input v-model="users.description"></el-input>
          </el-form-item>

          <el-form-item prop="content" style=" margin-left: 2px" label="内容">
            <div id ="editor"></div>
          </el-form-item>

        </el-form>

        <div slot="footer" style="text-align: center; margin-top: -10px">
          <el-button @click="FormAddInfo = false">取 消</el-button>
          <el-button type="primary" @click="onSubmit">确 定</el-button>
        </div>

      </el-dialog>

      <el-dialog title="修改新闻" :visible.sync="FormUpdateInfo" width="40%" @close="onClose01">
        <el-form label-width="80px" style="padding-right: 30px" ref="formRef" :rules="rules" :model="forms"
                 class="demo-form-inline">

          <el-form-item prop="title" style="margin-top: 30px;" label="标题">
            <el-input v-model="forms.title" disabled></el-input>
          </el-form-item>

          <el-form-item prop="description" style="margin-left: 2px" label="简介">
            <el-input v-model="forms.description"></el-input>
          </el-form-item>

          <el-form-item prop="content" style=" margin-left: 2px" label="内容">
            <div id = "editor"></div>
          </el-form-item>

        </el-form>

        <div slot="footer" style="text-align: center; margin-top: -10px">
          <el-button @click="FormUpdateInfo = false">取 消</el-button>
          <el-button type="primary" @click="onUpdate">确 定</el-button>
        </div>

      </el-dialog>

      <el-dialog title="新闻详情" :visible.sync="NewsInfo" width="40%" >
        <div class="w-e-text">
          <div v-html="content"></div>
        </div>

        <div slot="footer" style="text-align: center; margin-top: -10px">
          <el-button type="primary" plain @click="NewsInfo = false">确 定</el-button>
        </div>
      </el-dialog>

    </div>
  </div>
</template>

<script>
import request from "@/utils/request"
import E from "wangeditor"
import hljs from "highlight.js"

export default {
  data() {
    return {
      Info: JSON.parse(localStorage.getItem('user11') || '{}'),
      pageSize: 8,
      pageNum: 1,
      tableData: [],
      title: '',
      content: '',
      editor: '',
      description: '',
      total: 0,
      FormAddInfo: false,
      NewsInfo: false,
      user: JSON.parse(localStorage.getItem('user11') || '{}'),
      users: {},
      ids: [],
      forms: {},
      FormUpdateInfo: false,

      rules: {
        title: [
          {required: true, message: '请输入标题', trigger: 'blur'},
          {min: 2, max: 20, message: '长度在 2 到 4 个字符', trigger: 'blur'}
        ]
      }
    }
  },
  created() {
    this.load()
  },
  methods: {

    onClose() {
      //销毁编辑器
      this.editor.destroy()
      this.editor = null
    },

    onClose01() {
      //销毁编辑器
      this.editor.destroy()
      this.editor = null
    },

    showContent(content) {
      this.NewsInfo = true
      this.content = content
    },

    //批量删除
    deleteBatch() {
      if(this.ids.length === 0) {
        this.$message.warning('请选择要批量删除的数据')
        return
      }
      this.$confirm('确定批量删除吗？', '提示', {type: 'warning'}).then(() => {
        request.delete('/news/deleteBatch', {
          data:this.ids
        }).then(res => {
          if (res.code === 200) {
            this.$message.success('批量删除成功')
            this.load(1)
          } else {
            // 登录失败
            this.$message.error(res.message)
          }
        })
      }).catch(() => {
        this.$message({type: 'info', message: '已取消批量删除'});
      })
    },

    //批量删除获取数据
    handleSelectionChange(rows) {
      // 提取所有选中的 id 并拼接成字符串
      this.ids = rows.map(v => v.id);
    },

    FormAddInfoAn() {
      this.FormAddInfo = true,
      this.users = {}
      this.$nextTick(() => {
        this.editor = new E('#editor')
        this.editor.highlight = hljs
        this.editor.config.uploadImgServer= 'http://localhost:9090/file/editor/upload'
        this.editor.config.uploadFileName = 'file'
        this.editor.config.uploadImgHeaders = {
          token: this.user.token
        }
        this.editor.config.uploadImgParams = {
          type: 'img',
        }

        this.editor.config.uploadVideoServer = 'http://localhost:9090/file/editor/uploadVoid'
        this.editor.config.uploadVideoName = 'file'
        this.editor.config.uploadVideoServer = {
          token: this.user.token
        }
        this.editor.config.uploadVideoParams = {
          type: 'img',
        }
        this.editor.create()
      })
    },

    //删除单条数据
    handleDelete(id) {
      this.$confirm('确定删除吗？', '提示', {type: 'warning'}).then(() => {
        request.delete('/news/delete/' + id).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.load(1)
          } else {
            // 登录失败
            this.$message.error(res.message)
          }
        })
      }).catch(() => {
        this.$message({type: 'info', message: '已取消删除'});
      })
    },

    //编辑数据
    handleEdit(row) {
      this.FormUpdateInfo = true,
      this.forms = JSON.parse(JSON.stringify(row))
      this.$nextTick(() => {
        this.editor = new E('#editor')
        this.editor.highlight = hljs
        this.editor.config.uploadImgServer='http://localhost:9090/file/editor/upload'
        this.editor.config.uploadFileName = 'file'
        this.editor.config.uploadImgHeaders = {
          token: this.user.token
        }
        this.editor.config.uploadImgParams = {
          type: 'img',
        }

        this.editor.config.uploadVideoServer = 'http://localhost:9090/file/editor/uploadVoid'
        this.editor.config.uploadVideoName = 'file'
        this.editor.config.uploadVideoServer = {
          token: this.user.token
        }
        this.editor.config.uploadVideoParams = {
          type: 'img',
        }
        this.editor.create()
        this.editor.txt.html(row.content)
      })
    },
    //确认是否确认提交修改
    onUpdate() {
      this.$confirm('确定用户信息吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let content = this.editor.txt.html()
        this.forms.content = content
        //触发更新
        request.post('/news/update', this.forms).then(res => {
          if (res.code === 200) {
            this.$message.success('修改成功')
            //  浏览器页面自动更新
            this.FormUpdateInfo = false
            this.load()
          } else {
            // 登录失败
            this.$message.error(res.message)
          }
        })
      }).catch(() => {
        this.$message({type: 'info', message: '已取消修改'});
      })
    },

    returnInfo() {
      this.title = '',
          this.description = '',
          this.load()
    },
    load(pageNum) {
      this.pageNum = pageNum || 1
      request.get('/news/selectByPage', {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          title: this.title,
          description: this.description,
        }
      }).then(res => {
        this.tableData = res.data.list
        this.total = res.data.total
      })
    },
    handleCurrentChange(pageNum) {
      this.load(pageNum)
    },

    //  添加表单
    onSubmit() {
      //获取编辑框信息
      this.$refs.formRef.validate(valid => {
        if (valid) {
          let content = this.editor.txt.html()
          this.users.content = content
          this.$confirm('再次确定添加用户信息？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            //触发更新
            request.post('/news/add', this.users).then(res => {
              if (res.code === 200) {
                this.$message.success('添加成功')
                //  浏览器页面自动更新
                this.FormAddInfo = false
                this.load()
              } else {
                // 登录失败
                this.$message.error(res.message)
              }
            })
          }).catch(() => {
            this.$message({type: 'info', message: '已取消修改'});
          })
        }
      })
    },
  }
}
;
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 140px;
  height: 140px;
  line-height: 140px;
  text-align: center;
  border-radius: 50%;
  margin-top: -10px;
  margin-bottom: 10px;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
